app.controller('FinishDataTableController', FinishDataTableController);
function FinishDataTableController($scope, RESTService, $filter,$compile, $state, $modal, $rootScope, $translate) {
    // define value
    $scope.searchKey = "";

    // paging for service request
    $scope.dtOptions = {
        aaSorting: [],
        bFilter: false,
        bLengthChange: false,
        bSort: false,
        bStateSave: false,
        oLanguage: {
            sUrl: ("Cn" === $scope.locale ? "./l10n/datatables.Chinese.json" : "")
        },
        processing: true,
        serverSide: true,
        sAjaxDataProp: "data",
        ajax: function(data, callback) {
            $scope.servRequests = [];
            getCountServRequest();
            // prepare query variables
            var params = {
                status:"operated",
                like: $scope.searchKey,
                pageNo: data.start / data.length + 1,
                pageSize: data.length
            };
            var sort = [], i;

            if (0 !== data.order.length) {
                for (i in data.order) {
                    if (data.order.hasOwnProperty(i)) {
                        sort.push({
                            property: data.columns[data.order[i].column].data,
                            direction: data.order[i].dir.toUpperCase()
                        });
                    }
                }

                if (0 !== sort.length) {
                    params.sort = angular.toJson(sort);
                }
            }

            if (3 <= data.search.value.length) {
                params.filter = data.search.value;
            }
            // transmit to server
            RESTService.getResponse("/rest/servreq/getServReqs?" + $.param(params)).then(
                function(response) {
                    angular.forEach(response, function(item) {
                        item.No =   $scope.servRequests.length  + (params.pageNo * params.pageSize) - 9;
                        $scope.servRequests.push(item);
                    });
                    callback({
                        aaData: [],
                        draw: data.draw,
                        recordsTotal: $scope.rowCount,
                        recordsFiltered: $scope.rowCount
                    });
                    $scope.dtInstance.find("td.dataTables_empty").parent().hide(); // small hack for "aaData: []"
                });
        },
        fnCreatedRow: function(row) {
            $compile(row)($scope);
        },
        fnInitComplete: function() {
            $scope.$parent.dtInstance = this.fnSetFilteringDelay();
        }
    };
    // action list
    $scope.startSearch = function(param){
        $scope.searchKey = param;
        $scope.dtInstance.DataTable().ajax.reload();
    };
    function getCountServRequest(){
        var param = {
            status:"operated",
            like: $scope.searchKey
        };
        RESTService.getResponse("/rest/servreq/getServReqsCount?" + $.param(param)).then(function(response){
            if(undefined !== response){
                $scope.rowCount = response[0].count;
            }
        });
    }
    function reloadData (){
    	if($scope.dtInstance) {
        	$scope.dtInstance.DataTable().ajax.reload();
        }
    }

    $scope.startEditEvaluation = function(serv) {
        // console.log("test:",serv);
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'views/work/process_evaluation.html',
            controller: 'ModalInstanceCtrl',
            size: 'md',
            resolve: {
                items: function() {
                    return serv
                }
            }
        });
        modalInstance.result.then(function() {
        }, function() {
            $scope.dtInstance.DataTable().ajax.reload();
        })
    };
	
	$scope.openComplete = function(servReq) {
		$scope.servReq = servReq;
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'openComplete.html',
            controller: 'ModalInstanceCtrl',
            size: 'md',
            resolve: {
                items: function() {
                    return servReq
                }
            }
        });
        modalInstance.result.then(function() {
        	$scope.finishEvaluation($scope.servReq);
        }, function() {
        })
    };
	
    $scope.finishEvaluation = function(serv){
        var param = {
            servReq_Id: serv.servReq_Id
        };
        RESTService.postResponse("/rest/servreq/setFinish?", param).then(function(response) {
            if (undefined !== response) {
                reloadData();
            }
        });
    };

    $scope.open = function(attrs, model) {
        // model.scope = $scope;
        $modal.open(angular.extend({
            backdrop:'static',
            controller: "ModalInstanceCtrl",
            resolve: {
                items: function() {
                    return [Object(model)];
                }
            },
            scope : $scope
        }, attrs));
    };

    // share case
    $scope.sharePatient = function(a, b){
        var patient_Id = a.patient_Id ? a.patient_Id : a.patient_Id2;
        var params = {
            patient_Id:patient_Id
            ,friendId:b
        }
        console.log(params);
        RESTService.postResponse('/rest/chat/createChatMessageSharingPatient?', params).then(
            function (suc) {
                console.log(suc);
            });
    }
}